<template>
    <view class="call-container">
        <!-- 拨号中状态 -->
        <view v-if="callState === 'dialing'" class="state-container">
            <text class="calling-text">正在呼叫 {{ targetPhone }}...</text>
            <view class="dial-animation">
                <view class="circle" :style="{animationDelay: '0s'}"></view>
                <view class="circle" :style="{animationDelay: '0.2s'}"></view>
                <view class="circle" :style="{animationDelay: '0.4s'}"></view>
            </view>
            <button class="hangup-btn" @click="hangupCall">挂断</button>
        </view>
        
        <!-- 来电状态 -->
        <view v-if="callState === 'incoming'" class="state-container">
            <text class="calling-text">{{ fromPhone }} 正在呼叫您...</text>
            <view class="call-actions">
                <button class="refuse-btn" @click="hangupCall">挂断</button>
                <button class="accept-btn" @click="acceptCall">接听</button>
            </view>
        </view>
        
        <!-- 通话中状态 -->
        <view v-if="callState === 'talking'" class="state-container">
            <text class="calling-text">正在与 {{ talkingWith }} 通话中</text>
            <text class="call-duration">{{ formatDuration(callDuration) }}</text>
            <view class="call-controls">
                <button class="control-btn">静音</button>
                <button class="hangup-btn" @click="hangupCall">结束通话</button>
                <button class="control-btn">免提</button>
            </view>
        </view>
        
        <!-- 通话结束状态 -->
        <view v-if="callState === 'ended'" class="state-container">
            <text class="calling-text">{{ endReason }}</text>
            <button class="back-btn" @click="goBack">返回</button>
        </view>
    </view>
</template>

<script>
let websocket = null;
let timer = null;

export default {
    data() {
        return {
            myPhone: '', // 当前用户的号码（A 是虚拟号，B 是 13508644429）
            targetPhone: '', // 呼叫目标号码（A 是 13508644429，B 是 A 的虚拟号）
            fromPhone: '', // 来电号码（仅 B 来电时使用）
            talkingWith: '', // 正在通话的对象号码
            callState: 'dialing', // dialing/incoming/talking/ended
            callDuration: 0, // 通话时长（秒）
            endReason: '通话已结束',
            userId: null,
            userType: null,
            pay: null
        };
    },
    onLoad(options) {
		 console.log('通话页面接收的原始参数:', options);
        this.myPhone = options.myPhone;
        this.targetPhone = options.targetPhone;
        this.fromPhone = options.fromPhone;
        this.pay = options.pay;
        // 确定通话对象：呼入是 fromPhone，呼出是 targetPhone
        this.talkingWith = options.isIncoming ? options.fromPhone : options.targetPhone;
		    this.initWebSocket();
        
        // 读取用户信息（确保 userId 和 userType 有效）
        const storedUser = uni.getStorageSync('userInfo');
        this.userId = storedUser?.userId || null;
        this.fetchUserInfo();
        
        // 初始化 WebSocket
        this.initWebSocket();
        
        // 切换通话状态（呼入/呼出）
        if (options.isIncoming) {
            this.callState = 'incoming';
        } else {
            this.callState = 'dialing';
        }
    },
    onUnmounted() {
        // 页面销毁时关闭连接和定时器
        if (websocket) websocket.close();
        if (timer) clearInterval(timer);
    },
    methods: {
        // 获取用户信息（补充 userType）
        fetchUserInfo() {
            if (!this.userId) return;
            
            try {
                uni.request({
                    url: 'http://localhost:6006/user-client/api/loginInfo/getUserInfo',
                    method: 'POST',
                    data: { userId: this.userId },
                    header: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    success: (res) => {
                        this.userType = res.data?.data?.userType || '公客';
                        console.log('当前用户类型：', this.userType);
                    }
                });
            } catch (error) {
                console.error('获取用户信息异常：', error);
            }
        },
        
        // 初始化 WebSocket：连接当前用户的号码
        initWebSocket() {
            const wsuri = `ws://localhost:6008/phone-client/websocket/call/${this.myPhone}`;
            websocket = new WebSocket(wsuri);
            
            websocket.onopen = () => {
                console.log('通话页 WebSocket 连接成功');
                // 呼出时自动发送 call 消息
                if (this.callState === 'dialing') {
                    this.sendCallRequest();
                }
            };
            
            websocket.onmessage = (res) => {
                console.log('通话页收到消息：', res.data);
                this.handleMessage(res.data);
            };
            
            websocket.onclose = () => {
                console.log('通话页 WebSocket 连接关闭');
            };
            
            websocket.onerror = (err) => {
                console.error('通话页 WebSocket 错误：', err);
            };
        },
        
        // A 呼出时发送 call 消息
        sendCallRequest() {
            const message = JSON.stringify({
                type: 'call',
                from: this.myPhone, // A 的虚拟号码
                to: this.targetPhone, // 目标号码（13508644429）
                userId: this.userId || '',
                userType: this.userType || '公客',
                pay: this.pay || 0,
                time: new Date().getTime()
            });
            
            if (websocket.readyState === WebSocket.OPEN) {
                websocket.send(message);
                console.log('A 发送呼叫消息：', message);
            } else {
                // 连接未就绪时重试
                setTimeout(() => this.sendCallRequest(), 1000);
            }
        },
        
        // 处理收到的消息（answer/hangup）
        handleMessage(message) {
            try {
                const data = JSON.parse(message);
                
                switch (data.type) {
                    case 'answer':
                        // A 收到 B 的接听消息，切换到通话中
                        this.callState = 'talking';
                        this.startCallTimer(); // 开始计时
                        break;
                    case 'hangup':
                        // 收到挂断消息，结束通话
                        this.callState = 'ended';
                        this.endReason = '对方已挂断';
                        this.stopCallTimer(); // 停止计时
                        break;
                }
            } catch (e) {
                console.error('解析消息错误：', e, '原始消息：', message);
            }
        },
        
        // B 接听来电
        acceptCall() {
            this.callState = 'talking';
            this.startCallTimer();
            
            const message = JSON.stringify({
                type: 'answer',
                from: this.myPhone, // B 的号码（13508644429）
                to: this.fromPhone, // A 的虚拟号码
                userId: this.userId || '',
                userType: this.userType || '公客',
                pay: this.pay || 0,
                time: new Date().getTime()
            });
            
            if (websocket && websocket.readyState === WebSocket.OPEN) {
                websocket.send(message);
                console.log('B 发送接听消息：', message);
            }
        },
        
hangupCall() {
    // 核心逻辑：根据当前角色（拨打/接收）动态设置to
    let toPhone = '';
    // 若当前是呼出方（callState为dialing/talking，且是主动拨打）
    if (this.callState === 'dialing' || (this.callState === 'talking' && !this.fromPhone)) {
        toPhone = this.targetPhone;
    } 
    // 若当前是接收方（callState为incoming/talking，且是来电）
    else if (this.callState === 'incoming' || (this.callState === 'talking' && this.fromPhone)) {
        toPhone = this.fromPhone;
    }

    const message = JSON.stringify({
        type: 'hangup',
        from: this.myPhone,
        to: toPhone, // 动态设置的to
        userId: this.userId || '',
        userType: this.userType || '公客',
        pay: this.pay || 0,
        time: new Date().getTime()
    });
    
    if (websocket && websocket.readyState === WebSocket.OPEN) {
        websocket.send(message);
        console.log('发送挂断消息：', message);
    }
    
    this.callState = 'ended';
    this.endReason = this.callState === 'incoming' ? '已拒绝通话' : '已挂断通话';
    this.stopCallTimer();
},
        
        // 开始通话计时
        startCallTimer() {
            this.callDuration = 0;
            timer = setInterval(() => {
                this.callDuration++;
            }, 1000);
        },
        
        // 停止通话计时
        stopCallTimer() {
            if (timer) {
                clearInterval(timer);
                timer = null;
            }
        },
        
        // 格式化通话时长（mm:ss）
        formatDuration(seconds) {
            const min = Math.floor(seconds / 60);
            const sec = seconds % 60;
            return `${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`;
        },
        
        // 返回上一页
        goBack() {
            uni.navigateBack({ delta: 1 });
        }
    }
};
</script>

<style scoped>
.call-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    background-color: #f5f5f5;
    padding: 50rpx 20rpx;
}
.state-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
}
.calling-text {
    font-size: 36rpx;
    margin-bottom: 80rpx;
    color: #333;
    text-align: center;
}
.call-duration {
    font-size: 48rpx;
    margin: 50rpx 0;
    color: #007aff;
    font-weight: bold;
}
/* 拨号动画 */
.dial-animation {
    position: relative;
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 100rpx;
}
.circle {
    position: absolute;
    width: 100%;
    height: 100%;
    border: 4rpx solid #007aff;
    border-radius: 50%;
    opacity: 0;
    animation: dial 2s infinite ease-in-out;
}
@keyframes dial {
    0% { transform: scale(0); opacity: 1; }
    100% { transform: scale(1.5); opacity: 0; }
}
/* 按钮样式 */
.call-actions, .call-controls {
    display: flex;
    justify-content: space-around;
    width: 100%;
    margin-top: 100rpx;
}
.hangup-btn, .accept-btn, .refuse-btn, .control-btn {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    line-height: normal;
    border: none;
}
.accept-btn {
    background-color: #4cd964;
    color: #fff;
}
.refuse-btn, .hangup-btn {
    background-color: #ff3b30;
    color: #fff;
}
.control-btn {
    background-color: #e5e5ea;
    color: #333;
    width: 100rpx;
    height: 100rpx;
    font-size: 24rpx;
}
.back-btn {
    margin-top: 80rpx;
    background-color: #007aff;
    color: #fff;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 30rpx;
    width: 200rpx;
}
</style>